﻿using CoachingOrganizer.Logic.Common;
using CoachingOrganizer.Logic.Models.Tools.MoneyCalculation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoachingOrganizer.Logic.Logic.Tools.MoneyCalculation
{
    internal class ReportLogic
    {
        private readonly ReportModel _model;
        private readonly LogicExtender _logicExtender;
        private readonly MoneyCalculationLogic _upperLogic;
        
        public ReportModel Model
        {
            get { return _model; }
        }

        public MoneyCalculationLogic UpperLogic
        {
            get { return _upperLogic; }
        } 

        public ReportLogic(ReportModel model, LogicExtender logicExtender, MoneyCalculationLogic upperLogic)
        {
            _model = model;
            _logicExtender = logicExtender;
            _upperLogic = upperLogic;
            model.EnumeratePeriodReportsDelegate = EnumeratePeriodReports;
        }

        private IEnumerable<PeriodReportLogic> EnumeratePeriodReports()
        {
            int count = GetPeriodsCount();
            return EnumeratePeriodReports(count);
        }

        private IEnumerable<PeriodReportLogic> EnumeratePeriodReports(int count)
        {
            for (int i = 0; i < count; i++)
                yield return new PeriodReportLogic(_upperLogic.Model.StartDate, _upperLogic.Model.FinishDate, _model.CurrentReportPeriodSize, i, _logicExtender, this);
        }

        private int GetPeriodsCount()
        {
            if (_model.CurrentReportPeriodSize.TotalDays == StableMoneyFlowItemModel.AsDaysInYear)
            {
                int yearsDiff = _upperLogic.Model.FinishDate.Year - _upperLogic.Model.StartDate.Year;
                return _upperLogic.Model.FinishDate.DayOfYear < _upperLogic.Model.StartDate.DayOfYear ? yearsDiff : yearsDiff + 1;
            }
            if (_model.CurrentReportPeriodSize.TotalDays == StableMoneyFlowItemModel.AsDaysInMonth)
            {
                int yearsDiff = _upperLogic.Model.FinishDate.Year - _upperLogic.Model.StartDate.Year;
                int monthDiff = _upperLogic.Model.FinishDate.Month - _upperLogic.Model.StartDate.Month;
                return _upperLogic.Model.FinishDate.Day < _upperLogic.Model.StartDate.Day ? monthDiff + 12 * yearsDiff : monthDiff + 12 * yearsDiff + 1;
            }
            else
                return (int)((_upperLogic.Model.FinishDate - _upperLogic.Model.StartDate).TotalDays / _model.CurrentReportPeriodSize.TotalDays) + 1;

        }
    }
}
